package com.uliian.upyundemo.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.uliian.upyundemo.config.UpyunConfig;
import com.uliian.upyundemo.dto.UpyunPolicy;
import com.uliian.upyundemo.dto.UpyunTokenResult;
import com.uliian.upyundemo.utils.UpyunUtils;
import main.java.com.UpYun;
import main.java.com.upyun.FormUploader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.GsonJsonParser;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

@Service
public class UpyunSignService {
    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

    @Autowired
    private UpyunConfig upyunConfig;

    @Autowired
    private Gson gson;

    @Autowired
    private ObjectMapper jacksonObjectMapper;

    public UpyunTokenResult getSign() throws Exception {

        UpyunPolicy policy = new UpyunPolicy(this.upyunConfig.getBucketName(), UpyunPolicy.UpyunSaveKey.FileMd5,(int)(System.currentTimeMillis()/1000)+60*30);

        String policyJson = gson.toJson(policy).replace(" ","");
        //String policyJson =jacksonObjectMapper.writeValueAsString(policy);
        String date = getRfc1123Time();

        String operator = this.upyunConfig.getOperator();
        String secret = this.upyunConfig.getMd5Password();
        String uri = "/"+this.upyunConfig.getBucketName();
        String base64Policy = Base64.getEncoder().encodeToString(policyJson.getBytes("UTF-8"));

        String result = UpyunDemoService.sign(operator,secret,"POST",uri,"",base64Policy,"");
//        String result = UpyunUtils.sign("POST", date, "/"+this.upyunConfig.getBucketName(), this.upyunConfig.getBucketName(), this.upyunConfig.getOperator(), this.upyunConfig.getMd5Password(), "",policyJson);
        UpyunTokenResult upyunTokenResult = new UpyunTokenResult();
        upyunTokenResult.setDate(date);
        upyunTokenResult.setUri("/"+this.upyunConfig.getBucketName());
        upyunTokenResult.setToken(result);
        upyunTokenResult.setBase64Policy(Base64Coder.encodeString(policyJson));
        return upyunTokenResult;
    }

    public static String getRfc1123Time() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        return dateFormat.format(calendar.getTime());
    }
}
